<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Tab Communication A</title>
</head>
<body>
    <h1>Tab Communication A</h1>
    <button id="sendBtn" onclick="sendMessage()">Send TO B By BroadcastChannel</button>
    <button id="sendBtn2" onclick="sendMessage2()">Send TO B By ServiceWorker</button>

    <!-- 使用BroadcastChannel发送消息到B.html -->
    <script>
        const channel = new BroadcastChannel('tab-communication');
        function sendMessage() {
            channel.postMessage('Hello from Tab A!');
        }
    </script>

    <!-- 使用Service Worker发送消息到B.html -->
    <script>
        // 注册Service Worker
        if ('serviceWorker' in navigator) {
            window.addEventListener('load', () => {
                navigator.serviceWorker.register('service-worker.js')
                    .then((registration) => {
                        console.log('Service Worker registered with scope:', registration.scope);
                    })
                    .catch((error) => {
                        console.log('Service Worker registration failed:', error);
                    });
            });
        }

        function sendMessage2() {
            navigator.serviceWorker.ready.then((registration) => {
                registration.active.postMessage('Hello from Tab A!');
            });
        }

        // 监听来自Service Worker的消息
        navigator.serviceWorker.addEventListener('message', (event) => {
            console.log('Received message via Service Worker:', event.data);
        });
    </script>

    <!-- 使用localStorage共享数据 -->
     <script>
        setTimeout(() => {
            localStorage.setItem('sharedData', 'Hello from Tab A!' + new Date().getTime());
        },1000)
     </script>

     <script>
        window.open
     </script>
</body>
</html>